<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="接口名称" prop="apiName">
        <el-input
          v-model="queryParams.apiName"
          placeholder="请输入接口名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="api编码" prop="apiCode">
        <el-input
          v-model="queryParams.apiCode"
          placeholder="请输入api编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接口状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择执行方式" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="调用时间" prop="syncTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.callTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择调用时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['api_log:log:add']"-->
<!--        >新增-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
          :disabled="logList.length < 1"
          v-hasPermi="['api_log:log:remove']"
        >清空
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['api_log:log:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="logList" ref="fileTable"  @row-click="selectThisRow" @selection-change="handleSelectionChange":row-class-name="tabRowClassName">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="id"/>
      <el-table-column label="接口名称" align="center" prop="apiName"/>
      <el-table-column label="api编码" align="center" prop="apiCode"/>
<!--      <el-table-column label="请求参数" align="center" prop="requestParam"/>-->
      <el-table-column label="接口状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="调用时间" align="center" prop="callTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.callTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调用人" align="center" prop="callUser"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row,scope.index)"
            v-hasPermi="['api_log:log:query']"
          >详细
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详情调用日志对话框 -->
    <el-dialog title="API日志详情" :visible.sync="open" width="700px" append-to-body>
      <el-dialog
        width="50%"
        title="详情"
        :visible.sync="innerVisible"
        append-to-body>
        <span v-model="content" :title="content">{{content}}</span><br>
        <el-button v-clipboard:copy="content" v-clipboard:success="onCopy" v-clipboard:error="onError"
                   type="info" icon="el-icon-info">
          复制
        </el-button>
      </el-dialog>
      <el-form ref="form" :model="form" :rules="rules" label-width="200">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="接口名称:" prop="apiName">
              {{form.apiName}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="api编码:" prop="apiCode">
              {{ form.apiCode }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="请求参数:" prop="requestParam">
          <el-row :gutter="24">
            <el-col :span="24">
              <span>{{form.requestParam}}</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="响应数据:" prop="responseData">
          <el-row :gutter="24">
            <el-col :span="24">
              <span>{{form.responseData | ellipsis}}</span>
            </el-col>
          </el-row>
          <el-button v-if="form.responseData != 'null'" type="info" icon="el-icon-info" @click="openInnerVisible(form.responseData)">
            查看
          </el-button>
        </el-form-item>
        <el-form-item label="接口状态:">
          <el-radio-group disabled v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="异常信息:" prop="errorMsg">
          <el-row :gutter="24">
            <el-col :span="24">
              {{form.errorMsg | ellipsis}}
            </el-col>
          </el-row>
          <span v-model="form.errorMsg" :title="form.errorMsg"></span>
          <el-button v-if="form.errorMsg != null" type="info" icon="el-icon-info" @click="openInnerVisible(form.errorMsg)">
            查看
          </el-button>
        </el-form-item>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="调用人:" prop="callUser">
              {{form.callUser}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调用时间:" prop="callTime">
              {{parseTime(form.callTime)}}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listLog, getLog, delLog, addLog, updateLog, cleanCallApiLog} from "@/api/log/apiLog";

  export default {
    name: "ApiLog",
    components: {},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 接口调用日志表格数据
        logList: [],
        // 弹出层标题
        title: "",
        address: "",
        // 是否显示弹出层
        open: false,
        innerVisible: false,
        content: '',
        // 所属应用字典
        appTypeOptions: [],
        // 请求方式字典
        requerstTypeOptions: [],
        // 接口状态字典
        statusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          apiName: null,
          apiCode: null,
          callTime: null,
          appType: null,
          status : null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {}
      };
    },
    filters: {
      ellipsis(value) {
        if (!value) return "";
        if (value.length > 500) {
          return value.slice(0, 500) + "...";
        }
        return value;
      }
    },
    created() {
      this.getList();
      this.getDicts("app_type").then(response => {
        this.appTypeOptions = response.data;
      });
      this.getDicts("request_type").then(response => {
        this.requerstTypeOptions = response.data;
      });
      this.getDicts("sys_common_status").then(response => {
        this.statusOptions = response.data;
      });
    },
    methods: {
      /** 更改斑马纹 */
      tabRowClassName({row,rowIndex}){
        let index = rowIndex + 1;
        if(index %2 == 0){
          return 'two-color'
        }else {
          return "one-color"
        }
      },
      /** 查询接口调用日志列表 */
      getList() {
        this.loading = true;
        listLog(this.queryParams).then(response => {
          this.logList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 所属应用字典翻译
      appTypeFormat(row, column) {
        return this.selectDictLabel(this.appTypeOptions, row.appType);
      },
      // 请求方式字典翻译
      requerstTypeFormat(row, column) {
        return this.selectDictLabel(this.requerstTypeOptions, row.requerstType);
      },
      // 接口状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.open = false;
      },
      // 表单重置
      reset() {
        this.innerVisible = false;
        this.content = '';
        this.form = {
          id: null,
          apiName: null,
          apiCode: null,
          appType: null,
          requestParam: null,
          requerstType: null,
          responseData: null,
          status: 0,
          errorMsg: null,
          callTime: null,
          callUser: null
        };
        this.resetForm("form");
      },
      onCopy(e) { 　　 // 复制成功
        this.$message({
          message: '复制成功！',
          type: 'success'
        })
      },
      onError(e) {　　 // 复制失败
        this.$message({
          message: '复制失败！',
          type: 'error'
        })
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      selectThisRow(row){
        this.$refs.fileTable.toggleRowSelection(row);
      },
      /** 详细按钮操作 */
      handleView(row) {
        this.open = true;
        this.form = row;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加接口调用日志";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getLog(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改接口调用日志";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateLog(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addLog(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除接口调用日志编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delLog(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 清空按钮操作 */
      handleClean() {
        this.$confirm('是否确认清空所有API日志?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return cleanCallApiLog(this.queryParams);
        }).then(() => {
          this.getList();
          this.msgSuccess("清空成功");
        })
      },
      openInnerVisible(text){
        this.innerVisible = true;
        this.content = text;
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('api_log/log/export', {
          ...this.queryParams
        }, `api_log_log.xlsx`)
      }
    }
  };
</script>
